package com.cqhz.quwan.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.BallMatchBean
import com.cqhz.quwan.model.BallMatchListBean
import com.cqhz.quwan.mvp.BasketballLotteryContract
import com.cqhz.quwan.mvp.BasketballLotteryPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.interfaces.SelectBallChangeListener
import com.cqhz.quwan.ui.main.match.MatchAnalysisActivity
import com.cqhz.quwan.ui.widget.LoadMoreGoneView
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.displayTextColor
import com.gavin.com.library.PowerfulStickyDecoration
import com.gavin.com.library.listener.PowerGroupListener
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_basketball_lottery.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject


/**
 * 竞猜篮球列表选择页面
 * Created by Guojing on 2018/12/17.
 */
class BasketballLotteryActivity : GoBackActivity(), BasketballLotteryContract.View, HasDaggerInject<ActivityInject>, SelectBallChangeListener {


    @Inject
    lateinit var basketballLotteryPresenter: BasketballLotteryPresenter
    private var currentPage: Int = 0// 当前页面位置
    private var titles = arrayOf("混合过关", "单关", "胜负", "让分胜负", "大小分", "胜分差")
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var groups = ArrayList<ArrayList<BallMatchListBean>>()
    private var childrens = ArrayList<ArrayList<BallMatchBean>>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var mSelectList = ArrayList<BallMatchBean>()
    private var mMatchTotalNumber: Int = 0// 比赛场数
    private lateinit var mSelectChangeBean: BallMatchBean


    private val mHandler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                MSG_UPDATE_UI_SELECT -> {
                    childrens[mSelectChangeBean.pagePosition][mSelectChangeBean.adapterPosition] = mSelectChangeBean
                    adapters[mSelectChangeBean.pagePosition].notifyDataSetChanged()
                    setCheckedChangeText()
                }
                MSG_UPDATE_UI_BACK -> {
                    childrens[mSelectChangeBean.pagePosition][mSelectChangeBean.adapterPosition] = mSelectChangeBean
                    adapters[mSelectChangeBean.pagePosition].notifyDataSetChanged()
                    setCheckedChangeText()
                }
                else -> {
                }
            }
        }
    }


    companion object {
        const val REQUEST_SELECT = 0x1001
        const val REQUEST_SELECT_LOTTERY = 0x1002
        const val MSG_UPDATE_UI_SELECT = 0x10001
        const val MSG_UPDATE_UI_BACK = 0x10002
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "竞猜篮球"
    }

    override fun layout(): Int {
        return R.layout.activity_basketball_lottery
    }

    override fun initView() {
        basketballLotteryPresenter.attachView(this)

        currentPage = intent.getIntExtra(KeyContract.Position, 0)

        // 初始化页面元素和相应数据以及适配器
        for (i in 0 until titles.size) {
            initAdapter(i)
        }
        initPager()

        setOnClick()
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter(i: Int) {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据
        var groupList = ArrayList<BallMatchListBean>()
        var childList = ArrayList<BallMatchBean>()

        // 设置适配器
        when (i) {
            0 -> adapters.add(CommonAdapterHelper.getBasketballLotteryHHListAdapter(childList, 0, this))
            1 -> adapters.add(CommonAdapterHelper.getBasketballLotteryHHListAdapter(childList, 1, this))
            2 -> adapters.add(CommonAdapterHelper.getBasketballLotterySFListAdapter(childList, 2, this))
            3 -> adapters.add(CommonAdapterHelper.getBasketballLotterySFListAdapter(childList, 3, this))
            4 -> adapters.add(CommonAdapterHelper.getBasketballLotteryDXFListAdapter(childList, 4, this))
            5 -> adapters.add(CommonAdapterHelper.getBasketballLotterySFCListAdapter(childList, 5))
        }
        adapters[i].emptyView = emptyView
        adapters[i].setLoadMoreView(LoadMoreGoneView())
        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.adapter = adapters[i]
        adapters[i].setOnItemChildClickListener { _, view, position ->
            currentPage = vp_content.currentItem
            var item = childrens[currentPage][position]
            item.pagePosition = currentPage
            item.adapterPosition = position
            when (view.id) {
                R.id.action_expand -> {
                    item.isShowAnalysis = !item.isShowAnalysis
                    adapters[currentPage].notifyDataSetChanged()
                }
                R.id.action_goto_expand -> {
                    gotoBasketballSelectActivity(item)
                }
                R.id.action_goto_analysis -> {
                    MatchAnalysisActivity.start(this, item.matchId, item.leagueId)
                }
            }
        }

        // 刷新
        holder.refreshLayout.setOnRefreshListener {
            currentPage = vp_content.currentItem
            refreshCurrentPage()
        }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        groups.add(groupList)
        childrens.add(childList)
    }

    /**
     * 列表顶部固定的头布局
     */
    private fun getItemDecoration(): RecyclerView.ItemDecoration {
        var currentPage = vp_content.currentItem
        val groupListener = object : PowerGroupListener {
            override fun getGroupView(position: Int): View {
                val view = layoutInflater.inflate(R.layout.item_football_lottery_head, null, false)
                var tvMatchTime = view.findViewById(R.id.tv_match_time) as TextView
                if (childrens[currentPage].size > 0 && position <= childrens[currentPage].size - 1) {
                    val child = childrens[currentPage][position]
                    tvMatchTime.text = child.groupName
                } else {
                    tvMatchTime.text = "数据加载完毕"
                    tvMatchTime.setBackgroundColor(Color.parseColor("#ffffff"))
                }
                return view
            }

            override fun getGroupName(position: Int): String {
                if (childrens[currentPage].size > 0 && position <= childrens[currentPage].size - 1) {
                    val child = childrens[currentPage][position]
                    return child.groupName
                }
                return ""
            }
        }

        return PowerfulStickyDecoration.Builder
                .init(groupListener)
                .build()
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                currentPage = vp_content.currentItem
                mSelectList.clear()
                refreshCurrentPage()
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
        vp_content.currentItem = currentPage
        mSelectList.clear()
        refreshCurrentPage()
    }

    /**
     * 设置点击事件
     */
    private fun setOnClick() {

//        setTitleBarRightText("规则") {
//            val intent = Intent(this, WebViewActivity::class.java)
//            intent.putExtra(KeyContract.Title, "规则")
//            val url = "${API.basketballRule}"
//            intent.putExtra(KeyContract.Url, url)
//            startActivity(intent)
//        }
        // 清除
        action_clear.setOnClickListener {
            currentPage = vp_content.currentItem
            for (i in 0 until childrens[currentPage].size) {
                for (j in 0 until childrens[currentPage][i].selected!!.size) {
                    childrens[currentPage][i].selected!![j] = false
                }
                childrens[currentPage][i].selectedLabel = ""
                childrens[currentPage][i].selectedBasketString = null
                childrens[currentPage][i].selectedNumber = 0
            }
            adapters[currentPage].notifyDataSetChanged()
//            setCheckedChangeText()
        }
        // 确认
        action_confirm.setOnClickListener {
            if (mSelectList.size < (if (currentPage == 1) 1 else 2)) {
                showToast(if (currentPage == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                return@setOnClickListener
            }

            var intent = Intent(this, BasketballSelectedActivity::class.java)
            intent.putExtra(KeyContract.Title, titles[currentPage])
            intent.putExtra(KeyContract.Position, currentPage)
            intent.putParcelableArrayListExtra(KeyContract.List, mSelectList)
            startActivityForResult(intent, REQUEST_SELECT)
        }
    }

    /**
     * 当选择改变时，文字和列表改变
     */
    private fun setCheckedChangeText() {
        mSelectList.clear()
        for (i in 0 until childrens[currentPage].size) {
            if (childrens[currentPage][i].selectedNumber > 0) {
                mSelectList.add(childrens[currentPage][i])
            }
        }
        tv_select_number.text = when (mSelectList.size) {
            0 -> if (currentPage == 1) "请至少选 1 场比赛" else "请至少选 2 场比赛"
            1 -> {
                if (currentPage == 1) {
                    "已选 1 场"
                } else {
                    var text = "已选1场，还差 1 场可投"
                    displayTextColor(text, "1", " 1 ")
                }
            }
            else -> {
                "已选 " + mSelectList.size + " 场"
            }
        }
    }

    /**
     * 跳转到选择属性
     * @param bean
     */
    private fun gotoBasketballSelectActivity(bean: BallMatchBean) {
        val intent = Intent(this, if (currentPage != 5) BasketballSelectHHActivity::class.java else BasketballSelectSFCActivity::class.java)
        intent.putExtra(KeyContract.Bean, bean)
        startActivityForResult(intent, REQUEST_SELECT_LOTTERY)
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        basketballLotteryPresenter.getBasketballList(currentPage)
    }

    override fun setBasketballList(currentPage: Int, list: List<BallMatchListBean>) {
        // 初始化跳转页面
        groups[currentPage].clear()
        childrens[currentPage].clear()
        adapters[currentPage].setEnableLoadMore(true)
        if (holders[currentPage].refreshLayout.state.isHeader!!) {
            holders[currentPage].refreshLayout.finishRefresh()
        }

        var totalMatch = 0
        if (list.isNotEmpty()) {
            for (i in 0 until list.size) {
                for (j in 0 until list[i].match.size) {
                    var child = list[i].match[j]
                    var selected = mutableMapOf<Int, Boolean>()
                    for (k in 0 until 17) {
                        selected[k] = false
                    }
                    child.week = list[i].week
                    child.selected = selected
                    child.selectedLabel = ""
                    child.selectedBasketString = arrayListOf<String>()
                    child.groupName = list[i].date + " " + list[i].week + " " + list[i].count + "场比赛可投"
                    childrens[currentPage].add(child)
                    totalMatch++
                }
            }
            groups[currentPage].addAll(list)
        }
        mMatchTotalNumber = totalMatch

        // 需要在setLayoutManager()之后调用addItemDecoration()
        if (holders[currentPage].rvContent.itemDecorationCount > 0) {
            holders[currentPage].rvContent.removeItemDecorationAt(0)
        }
        holders[currentPage].rvContent.addItemDecoration(getItemDecoration())

        // 设置选中状态
        if (mSelectList.size > 0) {
            for (i in 0 until childrens[currentPage].size) {
                var selected = mutableMapOf<Int, Boolean>()
                for (k in 0 until 17) {
                    selected[k] = false
                }
                childrens[currentPage][i].selected = selected
                childrens[currentPage][i].selectedNumber = 0
                childrens[currentPage][i].selectedLabel = ""
                childrens[currentPage][i].selectedBasketString = arrayListOf<String>()
                for (j in 0 until mSelectList.size) {
                    if (childrens[currentPage][i].code == mSelectList[j].code) {
                        childrens[currentPage][i].week = mSelectList[j].week
                        childrens[currentPage][i].selected = mSelectList[j].selected
                        childrens[currentPage][i].selectedNumber = mSelectList[j].selectedNumber
                        childrens[currentPage][i].selectedLabel = mSelectList[j].selectedLabel
                        childrens[currentPage][i].selectedBasketString = mSelectList[j].selectedBasketString
                    }
                }
            }
            adapters[currentPage].notifyDataSetChanged()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    /**
     * 选择或取消
     * @param  bean
     */
    override fun onItemSelectChange(bean: BallMatchBean) {
        mSelectChangeBean = bean
        mHandler.sendEmptyMessage(MSG_UPDATE_UI_SELECT)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) when (requestCode) {
            REQUEST_SELECT -> {
                var type = data.getStringExtra(KeyContract.Type)
                var pagePosition = data.getIntExtra(KeyContract.Position, 0)
                if (type == "1") {
                    mSelectList.clear()
                    refreshCurrentPage()
                } else {
                    var list: ArrayList<BallMatchBean> = data.getParcelableArrayListExtra(KeyContract.List)
                    if (pagePosition == currentPage && list.size > 0) {
                        for (i in 0 until childrens[currentPage].size) {
                            var selected = mutableMapOf<Int, Boolean>()
                            for (k in 0 until 17) {
                                selected[k] = false
                            }
                            childrens[currentPage][i].selected = selected
                            childrens[currentPage][i].selectedNumber = 0
                            childrens[currentPage][i].selectedLabel = ""
                            childrens[currentPage][i].selectedBasketString = null
                            for (j in 0 until list.size) {
                                if (childrens[currentPage][i].code == list[j].code) {
                                    childrens[currentPage][i].week = mSelectList[j].week
                                    childrens[currentPage][i].selected = list[j].selected
                                    childrens[currentPage][i].selectedNumber = list[j].selectedNumber
                                    childrens[currentPage][i].selectedLabel = list[j].selectedLabel
                                    childrens[currentPage][i].selectedBasketString = list[j].selectedBasketString
                                }
                            }
                        }
                        adapters[pagePosition].notifyDataSetChanged()
                        setCheckedChangeText()
                    }
                }
            }
            REQUEST_SELECT_LOTTERY -> {
                // 刷新适配器
                mSelectChangeBean = data.getParcelableExtra<BallMatchBean>(KeyContract.Bean)
                if (mSelectChangeBean != null) {
                    mHandler.sendEmptyMessage(MSG_UPDATE_UI_BACK)
                }
            }
        }
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }
}
